package com.liu.yubi.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lqh
 * @since 2025-07-10 16:52
 * 消息队列配置对象
 */
@Configuration
public class MqQueueConfig {
    //普通队列
    public static final String COMMON_QUEUE="YuBi_common_queue"; //普通队列
    public static final String COMMON_EXCHANGE="YuBi_common_exchange";//普通交换机
    public static final String COMMON_ROUTE_KEY="YuBi_common_key"; //路由key

    //死信队列
    public static final String DEAD_QUEUE="YuBi_dead_queue"; //死信队列
    public static final String DEAD_EXCHANGE="YuBi_dead_exchange";//死信交换机
    public static final String DEAD_ROUTE_KEY="YuBi_dead_key"; //死信路由key


    // 声明普通队列
    @Bean("commonQueue")
    public Queue commonQueue() {
        Map<String, Object> args = new HashMap<> (4);
        //参数
        args.put ("x-message-ttl",20000); //设置消息的过期时间
        args.put ("x-dead-letter-exchange",DEAD_EXCHANGE);  //绑定死信交换机
        args.put ("x-dead-letter-routing-key",DEAD_ROUTE_KEY);  //绑定死信路由key
        args.put ("x-max-length",20);   //设置正常队列的大小
        return QueueBuilder.durable (COMMON_QUEUE).withArguments (args).build ();
    }

    // 声明普通交换机
    @Bean("commonExchange")
    public DirectExchange commonExchange() {
        return new DirectExchange(COMMON_EXCHANGE, true, false); // 持久化交换机
    }

    // 绑定队列和交换机（普通）
    @Bean
    public Binding commonQueueBindCommonExchange(@Qualifier("commonQueue") Queue commonQueue,
                           @Qualifier("commonExchange") DirectExchange commonExchange) {
        return BindingBuilder.bind(commonQueue).to(commonExchange).with(COMMON_ROUTE_KEY);
    }


    // 声明死信队列
    @Bean("deadQueue")
    public Queue deadQueue() {
        return QueueBuilder.durable (DEAD_QUEUE).build ();
    }

    // 声明死信交换机
    @Bean("deadExchange")
    public DirectExchange deadExchange() {
        return new DirectExchange(DEAD_EXCHANGE, true, false); // 持久化交换机
    }

    // 绑定队列和交换机（死信）
    @Bean
    public Binding deadQueueBindDeadExchange(@Qualifier("deadQueue") Queue deadQueue,
                           @Qualifier("deadExchange") DirectExchange deadExchange) {
        return BindingBuilder.bind(deadQueue).to(deadExchange).with(DEAD_ROUTE_KEY);
    }

}
